import pyqtgraph as pg
import sys
import copy
import os
from PyQt5.QtWidgets import *
from PyQt5.QtCore import pyqtSignal
import numpy as np

class CurveOverForm(QWidget):

    draw_signal = pyqtSignal(int)
    update_signal = pyqtSignal()

    def __init__(self):
        super(CurveOverForm, self).__init__()

        self.setWindowTitle("曲线叠加")
        self.resize(1200, 800)

        self.loadBtn = QPushButton(self)
        self.loadBtn.setText("加载")
        self.loadBtn.clicked.connect(self.loadData)
        self.cleanBtn = QPushButton(self)
        self.cleanBtn.setText("清空图像")
        self.cleanBtn.clicked.connect(self.cleanFigure)


        self.label = QLabel(self)

        self.combobox = QComboBox(self)
        self.combobox.addItems(["温度扭矩", "扭矩", "温度"])
        self.combobox.currentTextChanged.connect(self.updateFigure)

        self.torque = []
        self.temper = []

        self.canvasInit()
        self.draw_signal.connect(self.draw)
        self.update_signal.connect(self.updateFigure)
        self.layoutInit()

    def cleanFigure(self):
        self.p.clear()
        self.curves1 = []  # 存放所有的扭矩曲线
        self.curves2 = []  # 存放所有的温度曲线
        self.i = 0  # 表示第i条扭矩曲线
        self.j = 0  # 表示第j条温度曲线

        self.torque = []
        self.temper = []

        # 设置跟随鼠标移动的线
        self.vLine = pg.InfiniteLine(angle=90, movable=False)  # angle控制线相对x轴正向的相对夹角
        self.hLine = pg.InfiniteLine(angle=0, movable=False)
        self.p.addItem(self.vLine, ignoreBounds=True)
        self.p.addItem(self.hLine, ignoreBounds=True)

    def layoutInit(self):

        self.grid_layout = QGridLayout()
        self.grid_layout.addWidget(self.loadBtn, 0, 0)
        self.grid_layout.addWidget(self.cleanBtn, 0, 1)
        self.grid_layout.addWidget(self.combobox, 0, 2)
        self.grid_layout.addWidget(self.label, 0, 3)
        self.grid_layout.addWidget(self.canvas, 1, 0, 1, 4)
        self.setLayout(self.grid_layout)

    def draw(self, idx):
        """
        :param data: 曲线数据
        :param idx: 0表示扭矩，1表示温度
        :return:
        """
        if idx == 0:
            line = self.p.plot(self.torque[self.i], pen=self.color_torque[self.i], name="扭矩" + str(self.i + 1))
            self.i += 1
            self.curves1.append(line)
        else:
            line = self.p.plot(self.temper[self.j], pen=self.color_temper[self.j], name="温度" + str(self.j + 1))
            self.j += 1
            self.curves2.append(line)

        self.update_signal.emit()

    def updateFigure(self):
        """根据下拉框的选择选择不同的坐标系和曲线"""
        self.p.setTitle(self.combobox.currentText())
        if self.combobox.currentText() == "温度":
            self.p.setLabel(axis='left', text=u'温度 / ℃')
            self.p.setLabel(axis='bottom', text=u'时间 / s')
            self.p.setLabel(axis='right', text=u'')

            for line in self.curves1:
                line.hide()
            for line in self.curves2:
                line.show()

        elif self.combobox.currentText() == "扭矩":
            self.p.setLabel(axis='left', text=u'扭矩 / N·m')
            self.p.setLabel(axis='bottom', text=u'时间 / s')
            self.p.setLabel(axis='right', text=u'')

            for line in self.curves2:
                line.hide()
            for line in self.curves1:
                line.show()

        else:
            self.p.setLabel(axis='left', text=u'扭矩 / N·m')
            self.p.setLabel(axis='right', text=u'温度 / ℃')
            self.p.setLabel(axis='bottom', text=u'时间 / s')

            for line in self.curves1:
                line.show()
            for line in self.curves2:
                line.show()

    def canvasInit(self):
        """画板初始化"""
        self.canvas = pg.GraphicsLayoutWidget()
        # 启用抗锯齿
        pg.setConfigOptions(antialias=True)
        # 设置画板背景为白色
        self.canvas.setBackground("w")
        # 子图
        self.p = self.canvas.addPlot()

        # 设置跟随鼠标移动的线
        self.vLine = pg.InfiniteLine(angle=90, movable=False)  # angle控制线相对x轴正向的相对夹角
        self.hLine = pg.InfiniteLine(angle=0, movable=False)
        self.p.addItem(self.vLine, ignoreBounds=True)
        self.p.addItem(self.hLine, ignoreBounds=True)

        color = [[254, 15, 15], [250, 80, 7], [244, 155, 20], [246, 225, 37], [210, 252, 44], [144, 252, 37], [83, 252, 40], [40, 244, 60], [13, 251, 108], [46, 248, 187], [8, 254, 254], [28, 184, 250], [49, 127, 244], [44, 65, 252], [72, 28, 248], [151, 48, 253], [213, 50, 254], [253, 14, 229], [250, 11, 154], [252, 41, 104]]


        self.color_torque = color[:10]
        self.color_temper = color[10:]


        self.curves1 = []  # 存放所有的扭矩曲线
        self.curves2 = []  # 存放所有的温度曲线
        self.i = 0  # 表示第i条扭矩曲线
        self.j = 0  # 表示第j条温度曲线

        self.p.addLegend()
        self.vb = self.p.vb

        self.proxy = pg.SignalProxy(self.p.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)

    def mouseMoved(self, evt):
        """检测鼠标在图中的坐标"""
        pos = evt[0]  ## using signal proxy turns original arguments into a tuple
        if self.p.sceneBoundingRect().contains(pos):
            mousePoint = self.vb.mapSceneToView(pos)
            self.label.setText("<span style='font-size: 12pt'>x=%0.1f,   <span style='color: red'>y=%0.1f</span>" %
                               (mousePoint.x(), mousePoint.y()))
            self.vLine.setPos(mousePoint.x())
            self.hLine.setPos(mousePoint.y())

    def loadData(self):
        """选择文件夹加载数据"""
        directory = QFileDialog.getExistingDirectory()
        for root, dirs, files in os.walk(directory):
            for file in files:
                if file == "Torque.csv":
                    path = root + "/torque.csv"
                    data = np.loadtxt(path, delimiter=',')
                    t0 = copy.deepcopy(data[0])
                    t1 = copy.deepcopy(data[1])
                    data[0], data[1] = t1, t0
                    self.torque.append(data.T)

                    self.draw_signal.emit(0)
                if file == "Melt Temper.csv":
                    path = root + "/Melt Temper.csv"
                    data = np.loadtxt(path, delimiter=',')
                    t0 = copy.deepcopy(data[0])
                    t1 = copy.deepcopy(data[1])
                    data[0], data[1] = t1, t0
                    self.temper.append(data.T)
                    self.draw_signal.emit(1)
